<?php

// Day Period
define("LUNCH", 1);
define("DINNER", 2);
define("GRAVEYARD", 3);

$PERIOD = array(LUNCH => 'Lunch', DINNER => 'Dinner', GRAVEYARD => 'Graveyard');

define("ZERO", "<span class=empty>-</span>"); 

// Segundos em um dia
define("DAY", (60*60*24));

//Mensagens por paginas
define("MESSAGES_PER_PAGE", 10);

//Location state
define("REVIEW", 0);
define("ACCEPTED", 1);
define("TRASH", 2);

// Payment type
define("SINGLE", 0);
define("DAILY", 1);
define("WEEKLY", 2);
define("FIFTEENTH", 3);
define("MONTHLY", 4);
define("YEARLY", 5);

// Constants
define("OTHER", 0);
define("RENT", 1);
define("UNIFORM", 2);
define("SUPPLY", 3);
define("INSURANCE", 4);
define("COMMUNICATION", 5);
define("LABOR", 6);
define("ACCIDENT", 7);
define("REPORT", 9);
define("EVENT", 10);
define("EMPLOYEE", 11);
define("LOCATION", 12);
define("CONTACT", 13);
define("BOOT_MATERIAL", 14);
define("PARKING_MATERIAL", 15);
define("TICKET", 16);
define("CUSTOMER", 17);
define("OFFICE", 18);
define("ALL_LOCATIONS", 19);

$MONTH_NAMES = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dec");

$INC_CATEGORIES =
	array(OTHER => 'Other', RENT  => 'Rent', UNIFORM => 'Montly', REPORT => 'Extra Car');
$EXP_CATEGORIES =
	array(OTHER => 'Other', RENT => 'Rent', SUPPLY => 'Supply', ACCIDENT => 'Accident',
	INSURANCE => 'Insurance', COMMUNICATION => 'Communication', LABOR => 'Payroll Tax', OFFICE => "Office");
$REFERENCES_TO =
	array(OTHER => 'Other', EMPLOYEE => 'Employee', CUSTOMER => 'Customer',
	LOCATION => 'Location', REPORT => 'Report', EVENT => 'Event', 
    CONTACT => 'Contact', ALL_LOCATIONS => 'All Locations');
$DUEDATESPERIODS =
	array(DAILY => 'Dayly', WEEKLY => 'Weekly', FIFTEENTH => 'Fortnight',
	MONTHLY => 'Monthly', YEARLY =>'Yearly');

$SUPPLIES_CATEGORIES =
	array(UNIFORM => 'Uniform', TICKET => 'Ticket', PARKING_MATERIAL => 'Parking material',
	BOOT_MATERIAL => 'Boot material', OTHER => 'Other');

// Retorna pagina de erro(404)
function response_404()
{
    header('HTTP/1.1 404 Not Found');
    header("Status: 404 Not Found");
    die();
}

/*
 Get all locations in an Array with name and ID
*/
function get_all_locations()
{
    $locations = array();
    $resultado = query_bd("SELECT locations.id, contacts.name FROM locations, contacts " .
        "WHERE locations.locationcontact=contacts.id AND locations.operating=TRUE " .
        "ORDER BY contacts.name");
    while ($loc = mysql_fetch_array($resultado))
        $locations[] = $loc;
    unset($resultado);

    return $locations;
}

// Funcao para formatar um valor monetario: $ e duas casas decimais
// Se o valor é menor que zero, formata o numero com classe negativo(vermelho).
// Se o valor é maior que zerof, formata o numero com classe positivo(verde),
// Caso o numero seja zero, exibe apenas um "-"(nulo)
function show_money($value)
{
	if ($value == 0)
		return ZERO;
	else if ($value < 0)
		return "&#36;<span class=negativo>" . number_format($value, 2) . "</span>";
	else
		return "&#36;<span class=positivo>" . number_format($value, 2) . "</span>";
}

// Retorna a data de inicio do ultimo mes
function inicio_ultimo_mes()
{
	$data_atual = getdate();

	$mes = $data_atual['mon'] - 1;
	$ano = $data_atual['year'];
	if ($mes == 0)
	{
		$mes = 12;
		$ano --;
	}
	return strtotime($ano . sprintf("%02d", $mes) . "01");
}

// Retorna a data de termino do ultimo mes
function fim_ultimo_mes()
{
	$data_atual = getdate();

	$mes = $data_atual['mon'] - 1;
	$ano = $data_atual['year'];
	if ($mes == 0)
	{
		$mes = 12;
		$ano --;
	}
	return strtotime($ano . sprintf("%02d", $mes) .
	cal_days_in_month(CAL_GREGORIAN, $mes, $ano));
}

// Retorna a data de inicio da ultima quinzena
function inicio_ultima_quinzena()
{
	$data_atual = getdate();

	if ($data_atual['mday'] <= 15)
	{
		$mes = $data_atual['mon'] - 1;
		$ano = $data_atual['year'];
		if ($mes == 0)
		{
			$mes = 12;
			$ano --;
		}
		return strtotime($ano . sprintf("%02d", $mes) . "16");
	}
	else
	{
		return strtotime($data_atual['year'] .
		sprintf("%02d", $data_atual['mon']) . "01");
	}
}

// Retorna a data de termino da ultima quinzena
function fim_ultima_quinzena()
{
	$data_atual = getdate();

	if ($data_atual['mday'] <= 15)
	{
		$mes = $data_atual['mon'] - 1;
		$ano = $data_atual['year'];
		if ($mes == 0)
		{
			$mes = 12;
			$ano --;
		}
		return strtotime("{$ano}-{$mes}-" .
		cal_days_in_month(CAL_GREGORIAN, $mes, $ano));
	}
	else
	{
		return strtotime($data_atual['year'] .
		sprintf("%02d", $data_atual['mon']) . "15");
	}
}

// Retorna o dia seguinte a data
function next_day($timestamp = NULL)
{
	return $timestamp + DAY;
}

// Retorna a semana seguinte a data
function next_week($timestamp = NULL)
{
	return $timestamp + (DAY*7);
}

// Retorna a quinzena seguinte a data
function next_fifteenth($timestamp = NULL)
{
	$data_atual = getdate($timestamp);

	$dia_era = $data_atual['mday'];
	$dia = $data_atual['mday'] + 15;
	$mes = $data_atual['mon'];
	$ano = $data_atual['year'];

	if ($dia > cal_days_in_month(CAL_GREGORIAN, $mes, $ano))
	{
		$dia = $dia_era - 15;
		$mes++;
		if ($mes == 13)
		{
			$mes = 1;
			$ano++;
		}
	}
	return strtotime("{$ano}-{$mes}-{$dia}");
}

// Retorna o mes seguinte a data
function next_month($timestamp = NULL)
{
	$data_atual = getdate($timestamp);

	$mes = $data_atual['mon'] + 1;
	$ano = $data_atual['year'];

	if ($mes == 13)
	{
		$mes = 1;
		$ano++;
	}
	return strtotime("{$ano}-{$mes}-{$data_atual['mday']}");
}

// Retorna o ano seguinte a data
function next_year($timestamp = NULL)
{
	$data_atual = getdate($timestamp);

	$ano = $data_atual['year'] + 1;
	return strtotime($ano . sprintf("%02d", $data_atual['mon']) .
		sprintf("%02d", $data_atual['mday']));
}

// Calcula o labor e o labor expense do funcionario
function calculateLabor($employee_id, $from = NULL, $to = NULL)
{
	// Realiza consulta
	$resultado = query_bd("SELECT clocks.labor_expense, clocks.labor FROM clocks, reports WHERE " .
		"clocks.employee_id = {$employee_id} AND " .
		"clocks.report_id = reports.id AND reports.state = " . ACCEPTED .
		($from? " AND UNIX_TIMESTAMP(reports.reportdate) >= {$from}" : "") .
		($to? " AND UNIX_TIMESTAMP(reports.reportdate) <= {$to}" : "") );

	$LABOR = '00:00:00';
	$LABOR_EXP = 0.0;
	while ($dados = mysql_fetch_array($resultado))
	{
		// Soma com o tempo total
		$result = query_fetch("SELECT TIMEDIFF('{$dados['labor']}', '-{$LABOR}') AS sum");
		$LABOR = $result['sum'];

		// Soma pagamento
		$LABOR_EXP += $dados['labor_expense'];

		unset($dados);
	}
	unset($resultado);

	return array('labor' => $LABOR, 'labor_expense' => -$LABOR_EXP);
}

function formatTime($time)
{
	list($hor, $min, $seg) = explode(":", $time, 3);
	return ($hor=='00' && $min=='00'? ZERO : number_format(intval($hor)) . ":" . $min);
}

function decimalTime($time)
{
	list($hor, $min, $seg) = explode(":", $time);

	// Calcula o tempo decimal
	$dec = $hor;
	$dec += $min/60.0;
	$dec += $seg/3600.0;

	return $dec;
}

/**
 * @convert seconds to hours minutes and seconds
 *
 * @param int $seconds The number of seconds
 *
 * @return string
 */
function toTime($seconds)
{
    /*** return value ***/
    $ret = "-";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)
    {
        $ret = number_format($hours);
    }

    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
        $ret .= ":$minutes";
    }

    return $ret;
}

function sanitizeHTML($string)
{
	return str_replace("'", "&#39;", $string);
}

function sanitizeSQL($string)
{
	return str_replace("'", "\\'", $string);
}

?>
